package com.binc.testspring.study.mina.study2;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.Objects;

/**
 * FileName: MyHandler 服务端的业务处置对象
 *  必须实现ioHandler  但是实际使用上我们用不到这么多，我们推荐是继承IpHandlerAdapter即可；
 * Autho: binC
 * Date:  2022/3/25 9:40
 */
@Slf4j
// public class MyHandler implements IoHandler {
public class MyServerHandler extends IoHandlerAdapter {

    //这是要重写的   剩下的方法没必要了
    @Override
    public void messageReceived(IoSession session, Object obj) throws Exception {
        //使用了子自定义的协议包  自定义的编辑吗之后，我们handler收到的消息已经是com.binc.testspring.study.mina.study2.MyProtocolDecoder#decode 处理好的MyprotocolPackge对象了（com.binc.testspring.study.mina.study2.MyProtocolDecoder#decode将字节流专场了自定义对象）
        //服务端收到消息}的时候将然后给客户端一个返回
         MyProtocolPackage message = (MyProtocolPackage) obj;

        log.info(">>>>>>>>   server22222 session 收到消息"+message.toString()+"...");
        MyProtocolPackage returnMessage  = new MyProtocolPackage((byte)1,"return");

        session.write(returnMessage);
    }


    /** 下面的方法可以补充些的；为了测试效果才写着玩的 **********************************************************/
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        log.info(">>>>>>>>   server22222 session创建");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        log.info(">>>>>>>>   server22222 session打开");
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        log.info(">>>>>>>>   server22222 session关闭");
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
        log.info(">>>>>>>>   server22222 session   idle......");
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        // super.exceptionCaught(session, cause);
        log.info(">>>>>>>>   server22222 session 发生异常");
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
        log.info(">>>>>>>>   server22222 session发送消息"+((MyProtocolPackage)message).toString());
        session.closeNow();
    }
}
